#include "file.h"
#include "syscall.h"
#include "functions.h"
#include "console.h"
#include <string.h>
#include "frontend.h"
#include "proc.h"
#include "elf.h"
#include "config.h"
#include "mmap.h"
#include "riscv.h"
#include "buf.h"
#include "spinlock.h"
#include "console.h"
#include "file.h"

spinlock_t vdisk_lock;
file_t  img_file;
void
disk_rw(struct buf *b, int write)
{
  uint64 offset=b->blockno*BSIZE;
  //  printk("file def %d\n",img_file.refcnt);
  acquire(&vdisk_lock);
  if(write){
    //write the disk
    ssize_t ret=file_pwrite(&img_file,b->data,BSIZE,offset);
 //     printk("write %d bytes to fs.img %p \n",ret,offset);
  }else
  {
  
  //  printk("read start offset %p\n",offset);
    
    //read  the disk
    ssize_t ret = file_pread(&img_file, b->data, BSIZE, offset);
    if(ret!=BSIZE){
      printk("ret : %d\n",ret);
      panic("file_pread failed\n");
    }
    if(DEBUG_INODE){
      //  struct dinode  * dp=(struct dinode* )(b->data);
      //  printk("IPB %d\n",IPB);
      // for(int i=0;i<IPB;i++){
      //    printk("%p \n",*(dp+i));
      // }
      // printk("\n");
    }
    //printk("read %d bytes from fs.img %p \n",ret,offset);
  }
  // printk("file def %d\n",file.refcnt);
  // file_decref(file);
  // printk("file def %d\n",file.refcnt);
  release(&vdisk_lock);
}
